var stompClient = null;
var wsCreateHandler = null;
var uid = null;
var ipAndPort = null;

function connect() {
    var host = window.location.host; // 带有端口号
    uid = GetQueryString("uid");	//获取请求参数uid的值
    var socket = new SockJS("http://" + ipAndPort + "/websocket");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {	//连接服务器
            writeToScreen("connected: " + frame);
            /**
             * 原生Broker
             */
            // 群发
            // stompClient.subscribe('/topic', function (response) {
            // 	writeToScreen(response.body);
            // });

            //订阅主题（单发）
            stompClient.subscribe("/queue/" + uid + "/queue", function (response) {
                //将JSON字符串转换为Map类型
                var map = eval("(" + response.body + ")");
                writeToScreen("用户<" + map.sendUserId + ">发送给用户<" + map.receUserId + ">:\n" + map.msg);
            });

            //群发
            stompClient.subscribe('/topic/all', function (response) {
                //将JSON字符串转换为Map类型
                var map = eval("(" + response.body + ")");
                writeToScreen("用户<" + map.sendUserId + ">发送给用户<" + map.receUserId + ">:\n" + map.msg);
                // writeToScreen(response.body);
            });

            /**
             * rabbitMQ
             */
            // // rabbitMQ的/exchange/<ExchangeName>
            // stompClient.subscribe("/exchange/sendToUser/user" + userId, function (response) {
            // 	writeToScreen(response.body);
            // });
            //
            // //rabbitMQ的/queue/<queue>
            // stompClient.subscribe("/queue/user" + userId, function (response) {
            // 	writeToScreen(response.body);
            // });
            //
            // //rabbitMQ的/topic/<topicName>
            // stompClient.subscribe("/topic/user" + userId, function (response) {
            // 	writeToScreen(response.body);
            // });
            //
            // //rabbitMQ的/topic/<topicName>：群发
            // stompClient.subscribe("/topic/chat", function (response) {
            // 	writeToScreen(response.body);
            // });


        }, function (error) {		//自动进行心跳检查，连接出错后执行此方法
            wsCreateHandler && clearTimeout(wsCreateHandler);	//如果有重连操作，则清除
            wsCreateHandler = setTimeout(function () {	//连接出错：每嗝一秒进行一次重连，
                console.log("重连...");
                connect();
                console.log("重连完成");
            }, 1000);
        }
    )
}

// function disconnect() {
// 	if (stompClient != null) {
// 		stompClient.disconnect();
// 	}
// 	writeToScreen("disconnected");
// }

function writeToScreen(message) {		//输出到文本框
    if (DEBUG_FLAG) {
        $("#debuggerInfo").val($("#debuggerInfo").val() + "\n" + message);
    }
}

function GetQueryString(name) {			//获取请求参数
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}